package eu.szemraj.data.collections.list {
    import eu.szemraj.data.collections.ICollection;    
    import eu.szemraj.data.collections.ISortable;    
    import eu.szemraj.data.comparators.IComparator;    

    public class SortableArrayList extends ArrayList implements ISortable {

        private var _comparator:IComparator;

        public function SortableArrayList( comparator:IComparator, initObject:* = null ) {
        	
            super( initObject );
            _comparator = comparator;
        }

        override public function add(element:*):Boolean {
        	
            var added:Boolean = super.add( element );
            doSorting( ); 
            return added;
        }

        override public function addAtIndex(index:int, element:*):void {
        	
            super.addAtIndex( index, element );
            doSorting( );
        }

        override public function addAll(collection:ICollection):Boolean {
        	
            var added:Boolean = super.addAll( collection );
            doSorting( );
            return added;
        }

        override public function addAllAtIndex(index:int, collection:ICollection):Boolean {
        	
            var added:Boolean = super.addAllAtIndex( index, collection );
            doSorting( );
            return added;
        }

        public function sort( options:* = null ):Array {
        	
			if( options )
            	return _array.sort( _comparator.compare, options );
            else
            	return _array.sort(_comparator.compare );
		}

        public function sortOn( fields:*, options:* = null ):Array {
        	
            return _array.sortOn( fields, options );
        }

        protected function doSorting():void {
        	
            sort( );
        }
    }
}
